# -*- coding: utf-8 -*-
# @author: dengxixi
# @date:   2021-04-08
# @file:   WebApi 用来返回训练结果

import json
import urllib3


class WebTool(object):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36'
    }

    def __init__(self, url, auth=None):
        if auth:
            self.headers['Authorization'] = auth
        self._http = urllib3.PoolManager()
        self._url = url

    # 上传文件到
    def upload_file(self, url, file_key, file_type, file_name, file_path, form_data):
        http = self._http
        fields = dict()
        for k, v in form_data.items():
            fields[k] = (None, v, None)
        # print(fields, self.headers)
        with open(file_path, 'rb') as fp:
            file_data = fp.read()
            fields[file_key] = (file_name, file_data, file_type)
            # fields = {
            #     'local_path': (None, local_path, None),
            #     'frame': (file_name, file_data, "image/jpeg"),
            #     'oss_path': (None, oss_path, None)
            # }
            r = http.request('POST', url, fields=fields, headers=self.headers,
                             multipart_boundary='----WebKitFormBoundary7MA4YWxkTrZu0gW')
            return r.data.decode('utf-8') if r.data else None

    def post_json(self, data):
        if self._url is None or data is None:
            return 0, 'url or data is None'
        try:
            encoded_data = json.dumps(data).encode('utf-8')
            self.headers['content-type'] = 'application/json;charset=UTF-8'
            r = self._http.request('POST', self._url, body=encoded_data, headers=self.headers)
            return 1 if r.status == 200 else 0, r.data
        except Exception as e:
            return 0, str(e)


class ModelApi(WebTool):
    def send_train_progress(self, progress, error_msg=None, **kwargs):
        """ 发送进度
        { url_model ,progress ,error_msg, val_evaluation  """
        data = {**kwargs, 'progress': progress}
        if error_msg:
            data['error_msg'] = error_msg
        return self.post_json(data)
